import base from './base';
import * as API_REQ from '../apis/req';
import * as Util from './formUtil';
import * as continuationProcessUtil from './continuationProcessUtil';
import * as FieldUtil from './public/fieldUtil';
import * as DetailUtil from './public/detailUtil';
import {verifyRemark} from './signUtil';
import * as _ from './public/common';
import {CHOOSE_EXCEPTION_OPERATOR,HANDLE_REMIND,NEED_SHOW_CHART,SUBMIT_TYPE} from '../constants/type';
import objectAssign from 'object-assign';
import {getAntd, getEcCom,getLabel} from './convert';
import { verifyCustomRegisterEvent } from './public/globalUtil';
import * as LinkageControl from './public/linkageControl';

import {showAuthDialog,filterRequestAction} from "../util/secondAuthUtil";
import * as authTypes from "../constants/secondAuthType";
import {getSecondAuthConfig} from "../apis/secondAuth";
import * as type from '../constants/type';
import {Modal} from "antd";
import WfForm_Public from './public/interface'
import ReqFreeNodeSubmit from '../components/dialog/ReqFreeNodeSubmit';

//表单提交入口，先校验必填等信息
export const doSubmitForm = (para) => {
    const {commonParam, submitParam} = base.globalStore;
    const {message} = getAntd();
    const {actiontype, src, isaffirmance = '', closePage} = para;
    const {isSubmitDirectNode, lastnodeid, isHideInput, iscreate} = submitParam;
    const isFirstSubmit = iscreate == "1" ? "" : "0";
    const params = {...para, ...{isFirstSubmit}};

    if (src == 'submit' || isaffirmance == '1' || src == 'intervenor') {
        //提交前校验自定义函数
        if (!verifyCustomFun(src, isaffirmance)) {
            return false;
        }
        const isViewOnly = parseInt(commonParam.isviewonly || 0);
        const isAffirmanceSubmit = parseInt(commonParam.isaffirmance || 0);
        const intervenorright = parseInt(commonParam.intervenorright || 0);
        const needVerify = isViewOnly !== 1 && isAffirmanceSubmit !== 1;
        const submitFn = () =>{
            if (needVerify) {
                //校验必须新增明细
                if (!verifyMustAddDetail())
                    return false;
                //校验必填空值范围
                const emptyField = verifyRequiredEmptyField();
                if (emptyField !== "") {
                    window.setTimeout(()=>{
                        Util.showPrompt(emptyField, 1);     //明细可能需要切页，延时提示
                    },50);
                    return false;
                }
            }
            if (isSubmitDirectNode == "1") {
                params.SubmitToNodeid = lastnodeid;
            }
            //流程干预验证必填
            if (intervenorright > 0) {
                const result = verifyIntervenorInfo(submitParam);
                if (result.type == 0) {
                    message.warning(result.msg);
                    return false;
                }
            }
            //除表单字段外提交表单时的必填校验
            const emptyOtherPramas= verifyRequiredEmptyOtherParams()
            if(emptyOtherPramas.msg) {
                Util.scrollDom(emptyOtherPramas.dom,true,emptyOtherPramas.msg)
                return;
            }
            doSubmitReady(params);
        }
        //提交校验必填前，支持先执行自定义事件
        return needVerify ? verifyCustomRegisterEvent(WfForm_Public.OPER_BEFOREVERIFY, submitFn) : submitFn();
    } else {
        //标题字段放置在模板上且不为只读，则保存校验必填，其它情况后台接收到requestname为空的直接生成默认标题
        const { fieldAttrMap,cellInfo } = base.layoutStore;
        const requestnameViewAttr = fieldAttrMap.has("-1") && fieldAttrMap.get("-1").viewattr || 0;
        if (src === "save" && _.has(cellInfo, ["fieldCellInfo", "-1"]) && requestnameViewAttr > 1 && verifyRequestNameIsEmpty()) {
            Util.showPrompt("field-1", 1);
            message.warning(getLabel(386187, '请求标题字段未填值！'));
            return false;
        }
        doSubmitReady(params);
    }
}

//校验通过，准备提交
export const doSubmitReady = (params) => {
    const {src, actiontype, isaffirmance, type=""} = params;
    const {commonParam,changeSubmitParam} = base.globalStore;
    if (verifyRemark(params)) {
        //校验自定义拦截事件并判断是否继续提交
        verifyCustomRegisterEvent(params, () => {
            //签字意见相关流程，相关文档
            //暂时屏蔽接口
            let {needconfirm,selectNextFlow,isfreecomfirm} = commonParam;
            let isNeedFlowFreeNodeTips = jundgeNeedFlowFreeNodeTips(src,needconfirm == '1',selectNextFlow);
            if ((actiontype == "remarkOperation" && needconfirm == "1") || src == "intervenor" || isNeedFlowFreeNodeTips) {
                let content =  getLabel(19990, "确认是否提交?");
                if(isNeedFlowFreeNodeTips) {
                    // content = getNeedFlowFreeNodeTips(params);
                    content = <ReqFreeNodeSubmit/>;
                }
                getAntd().Modal.confirm({
                    content:content,
                    title: getLabel(131329, '信息确认'),
                    okText: getLabel(826, '确定'),
                    cancelText: getLabel(201, '取消'),
                    width:450,
                    onOk() {
                        doFileUpload(params);
                    },
                    onCancel() {
                      changeSubmitParam({SubmitToNodeid:"",flowToNextFreeNode:""});
                    }
                });
            } else if(src == "submit" && isfreecomfirm == "1" && type == ""){
                let content =  getLabel(533507, "自由流程最后一个节点，确认是否提交?");
                getAntd().Modal.confirm({
                    content:content,
                    title: getLabel(131329, '信息确认'),
                    okText: getLabel(826, '确定'),
                    cancelText: getLabel(201, '取消'),
                    width:450,
                    onOk() {
                        doFileUpload(params);
                    },
                    onCancel() {
                        changeSubmitParam({SubmitToNodeid:"",flowToNextFreeNode:""});
                    }
                });
            } else {
                doFileUpload(params);
            }
        });
    }
}

/**
 * 设置“提交到退回节点”的相关参数
 */
const setParam4SubmitDirect = () => {
    const {globalStore, secondAuthStore} = base;
    const {rightMenu} = globalStore;
    const {lastnodeid} = rightMenu;
    const {isSubmitDirect} = secondAuthStore;
    if (isSubmitDirect == 1) {      //说明是点击了"提交到退回节点"菜单/按钮
        globalStore.changeSubmitParam({SubmitToNodeid: lastnodeid});
    } else {
        globalStore.setSubmitToNodeId();
    }
}

//提交的方法重新修改，提交时，先判断是否需要二次验证
export const doFileUpload = (params) => {
    const {globalStore, secondAuthStore} = base;
    const {submitParam} = globalStore;
    const {workflowid, nodeid, requestid,f_weaver_belongto_userid,f_weaver_belongto_usertype} = submitParam;

    const {isAuthSuccess, isProtectSuccess} = secondAuthStore;
    //已验证通过或者已数据保护通过
    if (isAuthSuccess == 1 || isProtectSuccess == 1) {
        const {isEnableAuth, secondAuthType, isEnableProtect, protectType} = secondAuthStore;

        const configParams = secondAuthStore.params;
        const {authKey, qysSignWay = 2} = configParams;     //qysSignWay: 1,契约锁ukey签署，2，契约锁服务签署

        if (isProtectSuccess != 1 && isEnableProtect == 1) {      //仍然需要数据保护
            if (protectType == authTypes.CA_AUTH || (protectType == authTypes.QYS && qysSignWay == 1)) {     //CA数据保护 或者 契约锁ukey
                const isProtectDialog = 1;    //1表示打开的是CA数据保护的窗口
                //先保存表单数据
                let cakey = requestid + "_" + f_weaver_belongto_userid + "_" + f_weaver_belongto_usertype + "_" + new Date().getTime();
                globalStore.changeSubmitParam({isCAAuth: 1, CAKey: cakey});
                secondAuthStore.setCAAuthData({isProtectDialog});
                secondAuthStore.saveDataToStorage(cakey);   //将已经处理过的数据，存入localStorage
                doFileUpload0(params);
                return;
            } else if (protectType == authTypes.QYS && qysSignWay == 2) {     //契约锁数据保护
                const isProtectDialog = 1;    //1表示打开的是契约锁数据保护的窗口
                secondAuthStore.setCAAuthData({isProtectDialog});

                //弹出验证或者数据保护的窗口
                showAuthDialog(authTypes.SECOND_AUTH_DIALOG);
                return;
            }
        }

        //能运行到这里，说明已经做完了数据保护
        if (isEnableProtect == 1) {
            if (protectType == authTypes.CA_AUTH || (qysSignWay == 1 && protectType == authTypes.QYS)) {
                globalStore.changeSubmitParam({authKey, isProtectSuccess});
            }
        }

        //契约锁数据保护或者认证
        if (protectType == authTypes.QYS || secondAuthType == authTypes.QYS) {
            const {params: authParams} = secondAuthStore;
            const {qysSealId, qysSealImg, qysCertDetails} = authParams;
            globalStore.changeSubmitParam({qysSealId, qysSealImg, qysCertDetails, qysSignWay});
        }

        globalStore.changeSubmitParam({protectType, secondAuthType, isAuthSuccess});

        //设置“提交到退回节点”的相关参数
        const {src, actiontype} = params;
        if (actiontype == "requestOperation" && src == "submit") {
            setParam4SubmitDirect();
        }

        //验证签字意见，主要是需要将签字意见塞入到请求中，以及加入客户端的信息（ios，安卓等）
        verifyRemark({'needCheck':true,'needPrompt':false});

        doFileUpload0(params);
    } else {     //没有做过数据验证
        const {src} = params;
        getSecondAuthConfig({workflowid, nodeid, requestid,src}).then(data => {
            //每个参数的数据都设置一个默认值，避免节点删除，取不到配置信息时会导致错误的问题
            const {isEnableAuth = 0, secondAuthType = 0, isEnableProtect = 0, protectType = 0, qysSignWay = 2, authOperations = [], message = "", success} = data;
            const {Modal} = getAntd();

            if (success == "0") {
                if(!!message){
                    Modal.warning({
                        content: message,
                        okText: getLabel(83446, '确定'),
                        showClose: false
                    })

                    return;
                }
            }

            if(filterRequestAction(params,submitParam,authOperations)) {       //判断流程的操作类型(提交、保存、退回等)是否需要二次提交验证
                secondAuthStore.setDialogData({isEnableAuth, secondAuthType, isEnableProtect, protectType});

                if (isEnableAuth == 1) {        //二次认证
                    secondAuthStore.setCallbackParam(params);
                    secondAuthStore.setParams(data);

                    if (isEnableProtect == 1 && ((secondAuthType == authTypes.CA_AUTH && protectType == authTypes.CA_AUTH)
                        || (secondAuthType == authTypes.QYS && protectType == authTypes.QYS && qysSignWay == 1))) {    //如果同时还是CA数据保护或者 契约锁ukey签署
                        const isProtectDialog = 10;    //10表示打开的是 CA二次认证 + CA数据保护的窗口
                        //先保存流程表单的数据
                        let cakey = requestid + "_" + f_weaver_belongto_userid + "_" + f_weaver_belongto_usertype + "_" + new Date().getTime();
                        globalStore.changeSubmitParam({isCAAuth: 1, CAKey: cakey});
                        secondAuthStore.setCAAuthData({isProtectDialog});
                        secondAuthStore.saveDataToStorage(cakey);   //将已经处理过的数据，存入localStorage
                        doFileUpload0(params);
                        return;
                    } else if (secondAuthType == authTypes.QYS && isEnableProtect == 1 && protectType == authTypes.QYS && qysSignWay == 2) {     //如果同时还是契约锁数据保护
                        const isProtectDialog = 10;    //10表示打开的是 契约锁二次认证 + 契约锁数据保护的窗口
                        secondAuthStore.setCAAuthData({isProtectDialog});
                    }

                    //弹出验证或者数据保护的窗口
                    secondAuthStore.setCallbackFunc(doFileUpload);

                    //运行到这，就说明认证的方式和数据保护的方式不一致，先做认证
                    if (secondAuthType == authTypes.QYS && qysSignWay == 1) {
                        window.QYSUKeyUtil.showSignWin(secondAuthStore);
                    } else {
                        showAuthDialog(authTypes.SECOND_AUTH_DIALOG);
                    }
                } else {     //没有开启二次认证
                    if (isEnableProtect == 1) {
                        secondAuthStore.setCallbackParam(params);
                        secondAuthStore.setParams(data);
                        //目前数据保护的方式只有2种：CA保护，契约锁保护
                        if (protectType == authTypes.CA_AUTH || (protectType == authTypes.QYS && qysSignWay == 1)) {       //CA认证的方式或者 契约锁ukey签署
                            const isProtectDialog = 1;    //1表示打开的是CA数据保护的窗口
                            //先保存流程表单的数据
                            let cakey = requestid + "_" + f_weaver_belongto_userid + "_" + f_weaver_belongto_usertype + "_" + new Date().getTime();
                            globalStore.changeSubmitParam({isCAAuth: 1, CAKey: cakey});
                            secondAuthStore.setCAAuthData({isProtectDialog});
                            secondAuthStore.saveDataToStorage(cakey);   //将已经处理过的数据，存入localStorage
                            doFileUpload0(params);
                            return;
                        } else if (protectType == authTypes.QYS && qysSignWay == 2) {     //契约锁保护也需要弹出窗口
                            const isProtectDialog = 1;    //1表示打开的是契约锁数据保护的窗口
                            secondAuthStore.setCAAuthData({isProtectDialog});
                        }

                        //弹出验证或者数据保护的窗口
                        secondAuthStore.setCallbackFunc(doFileUpload);
                        showAuthDialog(authTypes.SECOND_AUTH_DIALOG);
                    } else {
                        doFileUpload0(params);
                    }
                }
            }else {
                doFileUpload0(params);
            }
        });
    }
    //二次验证完成
    /*if (isAuthSuccess == 1) {
        const params0 = secondAuthStore.params;
        const {protectType} = params0;
        if (protectType == authTypes.CA_AUTH) {    //CA数据保护
            const {authKey} = params0;
            globalStore.changeSubmitParam({authKey, isAuthSuccess});
        }

        globalStore.changeSubmitParam({protectType});

        doFileUpload0(params);
    } else {
        getSecondAuthConfig({workflowid, nodeid, requestid}).then(data => {
            const {isEnableAuth, secondAuthType, isEnableProtect,protectType} = data;

            //如果CA保护数据，那么暂时认为数据验证也是CA
            if (isEnableProtect == 1 && protectType == authTypes.CA_AUTH) {
                let cakey = requestid + "_" + f_weaver_belongto_userid + "_" + f_weaver_belongto_usertype + "_" + new Date().getTime();
                globalStore.changeSubmitParam({isCAAuth: 1, CAKey: cakey});
                const {WeaTools} = getEcCom();
                const {ls} = WeaTools;
                ls.set(cakey, params);   //将流程提交的参数，存入localStorage
                doFileUpload0(params);
            } else if (isEnableAuth == 1) {     //如果只是二次认证，那么即使是CA认证，也是弹出窗口
                secondAuthStore.setCallbackFunc(doFileUpload);
                secondAuthStore.setCallbackParam(params);
                secondAuthStore.setParams(data);
                showAuthDialog(authTypes.SECOND_AUTH_DIALOG);
            } else {
                if(isEnableProtect == 1){
                    globalStore.changeSubmitParam({protectType});
                }
                doFileUpload0(params);
            }
        });
    }*/
}

//上传附件，上传完成后提交表单
const doFileUpload0 = (params) => {
    const {globalStore, layoutStore} = base;
    const {btnDisabled,setBtnDisabled} = globalStore;
    if(btnDisabled) {
        return false;
    }
    setBtnDisabled(true);
    globalStore.setLoading(true);
    if (typeof(startUploadAll) == "function") {
        startUploadAll();	//上传附件
    }
    let timer = setInterval(() => {
        //检测附件是否上传完成
        const {mainData, fieldAttrMap} = layoutStore;
        let uploadArr = new Array();
        mainData.forEach((fieldObj, k) => {
            const fieldid = k.substring(5);
            if (fieldAttrMap.has(fieldid)) {
                const fieldAttr = fieldAttrMap.get(fieldid);
                const {variable} = fieldObj;
                if (fieldAttr.htmltype === 6 && variable.has("fileUploadStatus"))
                    uploadArr.push(variable.get("fileUploadStatus"));
            }
        });
        const failedArr = uploadArr.filter(o => o !== "uploaded");
        //处理上传失败的情况
        //正在上传中
        const uploadingArr = uploadArr.filter(o => o === "uploading");
        //上传失败
        const errorArr = uploadArr.filter(o => o === "error");
        if(uploadingArr.length === 0 && errorArr.length > 0) {
            clearInterval(timer);
            setBtnDisabled(false);
            globalStore.setLoading(false);
        }
        if (failedArr.length === 0) {
            doSubmitPost(params);
            clearInterval(timer);
        }
    }, 100);
}

//表单提交请求至后台
export const doSubmitPost = (params) => {
    LinkageControl.verifyLinkageFinished(()=>{
        const {src, actiontype,isAddSign = 0,saveCallFun} = params;
        delete params['saveCallFun'];
        const {globalStore} = base;
        const {browserVersion,commonParam, submitParam, rightMenu, changeSubmitParam} = globalStore;
        const {signatureAttributesStr, signatureSecretKey, selectNextFlow} = commonParam;
        const {isFree} = rightMenu;
        const formDatas = generateFormData();   //表单字段参数
        const remarkQuote = getRemarkQuoteData();
        const allParams = objectAssign({}, submitParam, remarkQuote, params, formDatas, {
            src,
            signatureAttributesStr,
            signatureSecretKey,
            selectNextFlow
        });
        if(isAddSign == 1) allParams.selectNextFlow = 0;
        globalStore.setLoading(true);
        const submitBeginTime = new Date().getTime();
        API_REQ.reqOperate(actiontype, allParams).then((result = {}) => {
            //记录耗时信息
            const duration = new Date().getTime() - submitBeginTime;
            if(!commonParam.belongTest){
                try{
                    const durationParams = {
                        url: window.location.href,
                        moduleType: 6,
                        clientType: browserVersion,
                        allTc: duration,
                        param: JSON.stringify(allParams)
                    };
                    API_REQ.writeDurationTimeInfo(durationParams);
                }catch(e){}
            }
            const {data,errorInfo = '系统错误，请联系管理员！',errorType = ''} = result;
            if(data) {
                const {type, resultInfo = {}, testParams = {}} = data;
                const requestid = parseInt(submitParam.requestid) <= 0 ? resultInfo.requestid : submitParam.requestid;

                //流程连续处理，保存表单后切换流程
                if(params.continuationSwitchType && src == "save" && type === "SUCCESS") {
                    continuationProcessUtil.switchRequest(params.continuationSwitchType);
                    return;
                }

                const doRefreshReq = () =>{
                    Util.reloadRequestPage({...testParams, ...resultInfo}, false);
                }
                //编辑锁定保存操作关闭页面
                if (actiontype == "requestOperation" && src == "save" && params.closePage === true) {
                    Util.closeRequestPage(false, {requestid});
                    return;
                }
                //保存成功后，触发子流程或新建流程
                if (actiontype == "requestOperation" && src == "save" && saveCallFun) {
                    saveCallFun();
                    return;
                }
                if (testParams.belongTest === true) {
                    try {
                        parent.window.workflowAutoTestUtil.returnStatus(type);
                    } catch (e) {
                        if (window.console) console.log(e);
                    }
                }

                //更新操作信息
                changeSubmitParam(data.submitParams);
                if (type === "FAILD") {
                    doRefreshReq();
                } else if (type === "SUCCESS") {
                    //关闭弹窗
                    closeAllDialog()
                    //流程提醒
                    const doRemind = (reqId,callBack)=>{
                        let remindParams  = {};
                        remindParams[HANDLE_REMIND] = true;
                        remindParams[SUBMIT_TYPE] = src;
                        remindParams['callBackActions'] = callBack;
                        globalStore.updateCommonParam('requestid',reqId);
                        globalStore.batchControlVariableMap(remindParams);
                    };

                    const {isaffirmance = '', isNextNodeOperator = false, isShowChart = '0', isCAAuth = '0',needRemind = false} = resultInfo;
                    if(resultInfo.selectNextFlow == "1" && (src != "save" || resultInfo.isaffirmance == "1") && resultInfo.isaffirmanceSrc != 'reject' && src != 'reject') {//用户选择下一节点流转
                        if(allParams.nodeid && data.messageInfo && (allParams.nodeid != data.messageInfo.nodeIds || data.messageInfo.hasPassThisNode) && !allParams.SubmitToNodeid) {
                            showSelectNextFlowDialog(data);
                        } else {//能流转到下一节点才弹出流转设置弹框
                            doSubmitReady({src: "submit", actiontype: "requestOperation", selectNextFlow : '1'});
                        }
                    }else if (resultInfo.isaffirmance != "1" && (actiontype == "requestOperation" && src == "save") || isNextNodeOperator || isCAAuth == "1") {//提交需确认
                        if(isNextNodeOperator && needRemind){
                            doRemind(requestid,()=>{
                                doRefreshReq();
                            });
                        }else{
                            doRefreshReq();
                        }
                        if(isNextNodeOperator)
                            Util.reloadListPage();
                    }  else if(resultInfo.isaffirmance == "1" ) {
                        if(isNextNodeOperator && needRemind){
                            doRemind(requestid,()=>{
                                showEnsureSubitDialog(data);
                            });
                        }else{
                            showEnsureSubitDialog(data);
                        }
                        if(isNextNodeOperator)
                            Util.reloadListPage();
                    } else {
                        if (testParams.belongTest === true) {     //流程测试只刷页面
                            Util.reloadRequestPage(testParams, false);
                        } else if (needRemind){
                            doRemind(requestid,()=>{
                                isShowChart === '1' && Util.showChart(requestid);
                                isShowChart === '0' && Util.closeRequestPage(false, {requestid, source:"submit"});
                                isShowChart === '3' && doRefreshReq();
                            });
                            Util.reloadListPage();
                        } else if (isShowChart === "1") {
                            globalStore.setCloseNeedPrompt(false);
                            //刷新流程图
                            Util.reloadListPage();
                            Util.showChart(requestid);
                        } else if(isShowChart === "3"){
                            globalStore.setCloseNeedPrompt(false);
                            Util.reloadListPage({needReloadList:true});
                            doRefreshReq();
                        } else{
                            Util.closeRequestPage(false, {requestid, source:"submit"});
                        }
                    }
                } else if (type === "SEND_PAGE") { //无权限
                    window.location.href = data.sendPage;
                } else if (type === "WF_LINK_TIP") { //出口提示
                    let msgcontent = resultInfo.msgcontent || "";
                    msgcontent = msgcontent.replace(/\\n/ig, "</br>");
                    const {controlVariableMap,variableMap} = globalStore;
                    controlVariableMap('wflinkTipOkCount',0);
                    getAntd().Modal.confirm({
                        content: <div dangerouslySetInnerHTML={{__html: msgcontent}}></div>,
                    title: getLabel(131329, '信息确认'),
                        okText: getLabel(826, '确定'),
                        cancelText: getLabel(201, '取消'),
                        onOk() {
                        let wflinkTipOkCount = variableMap.get('wflinkTipOkCount');
                        if(wflinkTipOkCount == 0){
                            controlVariableMap('wflinkTipOkCount',1);
                            changeSubmitParam({isFirstSubmit: 1, requestid: resultInfo.requestid});
                            doSubmitReady({src, actiontype: "requestOperation", type});
                        }
                    },
                    onCancel() {}
                });
                } else if (type === "R_CHROSE_OPERATOR") {    //异常处理选人(后续替换)
                    const {needChooseOperator, ehnextnodeid} = resultInfo;
                    if (needChooseOperator == "y")
                        chooseExceptionOperator(ehnextnodeid);
                } else if (type === "DELETE") {
                    Util.reloadListPage();
                    getAntd().Modal.warning({
                        content: resultInfo.label,
                        okText: getLabel(826, '确定'),
                        title: getLabel(131329, '信息确认'),
                        cancelText: getLabel(201, '取消'),
                        showClose: false,
                        onOk() {
                            Util.closeRequestPage(false, {source:"delete"});
                        }
                    });
                } else if (type === "ASYNC_SUBMIT") {
                    Util.closeRequestPage(false, {source:"submit"});
                }
            } else {
                if(errorType === '') {
                    const {Modal} = getAntd();
                    Modal.error({
                        content: errorInfo,
                        okText:getLabel(826, '确定'),
                        title:getLabel(15172, '系統提示')
                    });
                }
            }
            globalStore.setLoading(false);
            globalStore.setBtnDisabled(false);
        });
    });
}

const closeAllDialog = () => {
    const { controlDialogVisible } = base.globalStore;
    controlDialogVisible(type.FREE_WORKFLOW_SIMPLE, false);
}

//用户指定下一节点操作者
const showSelectNextFlowDialog = (data) => {
    const {selectNextFlowStore, globalStore} = base;
    const {changeSubmitParam} = globalStore;
    const { testParams = {} } = data;
    const {message} = getAntd();
    selectNextFlowStore.setBaseParams(globalStore.baseParam);
    let commonParam = globalStore.commonParam;
    if(commonParam.requestid == -1) {
        commonParam.requestid = data.resultInfo.requestid;
    }
    selectNextFlowStore.setCommonParams(commonParam);
    selectNextFlowStore.setNextNodeIds(data.messageInfo.nodeIds);
    if(data.messageInfo.nodeIds) {
        selectNextFlowStore.setCanFlowNextNode(true);
    }
    selectNextFlowStore.setConfirmEvent((nextNodeParams) =>{
        changeSubmitParam(nextNodeParams);
        doSubmitForm({src: "submit", actiontype: "requestOperation", isSelectNextFlow : '1'});
        //if(testParams.belongTest === true) {
            globalStore.controlDialogVisible(type.SELECT_NEXTFLOW, false);
            message.destroy();
        //}
    });
    selectNextFlowStore.setCancelEvent(() =>{
        Util.reloadRequestPage({requestid : data.resultInfo.requestid}, true);
        globalStore.controlDialogVisible(type.SELECT_NEXTFLOW, false);
    });
    globalStore.controlDialogVisible(type.SELECT_NEXTFLOW, true);		//需最后显示弹窗
}
//提交需确认弹框
const showEnsureSubitDialog = data => {
    const { ensureSubmitStore, globalStore, smartGuessWfStore } = base;
    const { setPromptInfo, controlDialogVisible } = globalStore;
    const {message} = getAntd();
    globalStore.commonParam.requestid = data.submitParams.requestid;
    let commonParam = globalStore.commonParam;
    let srcSource =   data.resultInfo && data.resultInfo.isaffirmanceSrc || 'submit';
    setPromptInfo(data.messageInfo);
    smartGuessWfStore.init({...commonParam, ...data.submitParams}); //参数初始化
    //打开窗口
    const showDialogCallBack = () => {
        controlDialogVisible(type.ENSURE_SUBMIT, true);
        ensureSubmitStore.setConfirmEvent(() =>{
            doSubmitForm({src: srcSource, actiontype: "requestOperation"});
            globalStore.controlDialogVisible(type.ENSURE_SUBMIT, false);
            message.destroy();
        });

        ensureSubmitStore.setCancelEvent(() =>{
            // Util.reloadRequestPage({requestid : data.resultInfo.requestid}, false);
            globalStore.controlDialogVisible(type.ENSURE_SUBMIT, false);
        });
    }
    //保存表单后，需要将明细表的keyid同步回来，否则会出现明细重复保存的情况
    updateDetailKeyId(showDialogCallBack,data.insertDetailDatasInfo);
}

//更新明细表的keyid
const updateDetailKeyId = (callback,dateilKeyDatas) => {
    const { globalStore, layoutStore } = base;
    const { commonParam } = globalStore;
    const { detailMap } = layoutStore;
    let detailmark = "";
    detailMap.keys().map(v =>{
        detailmark += v+",";
    });
    if(detailmark !== "") {
        detailmark = detailmark.substring(0, detailmark.length-1);
    }

    let needUpdate = commonParam.iscreate == '1';
    if(detailmark !== "" && !needUpdate) {
        needUpdate = detailmark.split(",").some(detailMark => {
            const detailObj = detailMap.get(detailMark);
            const { rowInfo,indexnum } = detailObj;
            return indexnum > 0 && rowInfo.keys().some(rowkey =>{
                const rowData = rowInfo.get(rowkey);
                //存在无keyid的明细数据
                return !rowData.get('keyid') || rowData.get('keyid') <= 0;
            });
        })
    }

    if(detailmark !== "" && needUpdate) {
		let shortRowKey = (a,b) => {
			return a.substring(4) - b.substring(4);
		}

		let existKeys = [];

		detailMap.keys().map((detailKey) => {
			const idList = dateilKeyDatas[detailKey];
			const detailObj = detailMap.get(detailKey);
			const { rowInfo,indexnum } = detailObj;
			indexnum > 0 && rowInfo.keys().sort(shortRowKey).map((rowkey, index) =>{
				const rowData = mobx.toJS(rowInfo.get(rowkey));
				if((!rowData.keyid || rowData.keyid == 0) && existKeys.indexOf(rowData.keyid) == -1) {
					layoutStore.detailMap.get(detailKey).rowInfo.get(rowkey).set('keyid', idList[(index-existKeys.length)]);
				} else {
					existKeys.push(rowData.keyid);
				}
			});
		})

		callback();
    } else {
        callback();
    }
}

//异常处理选择操作者弹窗
const chooseExceptionOperator = (ehnextnodeid) => {
    const {globalStore, ehOperatorStore} = base;
    const {changeSubmitParam, commonParam={}, secLevelInfo={}} = globalStore;
    ehOperatorStore.setBaseParams({ehnextnodeid: ehnextnodeid, requestid : commonParam.requestid, secLevel : secLevelInfo.secLevel});
    ehOperatorStore.setCallBackEvent((ehparams) => {
        globalStore.controlDialogVisible(CHOOSE_EXCEPTION_OPERATOR, false);
        changeSubmitParam(ehparams);
        doSubmitReady({src: "submit", actiontype: "requestOperation"});
    });
    globalStore.controlDialogVisible(CHOOSE_EXCEPTION_OPERATOR, true);
}
window.chooseExceptionOperator = chooseExceptionOperator;

//校验自定义函数
export const verifyCustomFun = (src, isaffirmance) => {
    //post前调用公共方法
    let ischeckok = true;
    // if(typeof(doBeforeReqSubmt) == "function"){
    //     const { commonParam } = base.globalStore;
    //     ischeckok = doBeforeReqSubmt(commonParam);
    // }
    //old
    if (src === 'submit' || isaffirmance === '1') {
        if (typeof(checkCustomize) == "function") {
            ischeckok = checkCustomize();
        }
        // if(typeof(checkCarSubmit) == "function"){
        //     ischeckok = checkCarSubmit();
        // }
    }
    return ischeckok;
}

//干预提交验证
export const verifyIntervenorInfo = (submitParam) => {
    const {submitNodeId = '', Intervenorid = ''} = submitParam;
    let result = {type: 1};
    if (_.trim(submitNodeId).length === 0) {
        result.type = 0;
        result.msg = getLabel(386188, '"流转至节点"未填写');
    }
    if (_.trim(Intervenorid).length === 0) {
        result.type = 0;
        result.msg = getLabel(386189, '"流转至节点操作者"未填写');
    }
    return result;
}

//提交校验必须新增明细
export const verifyMustAddDetail = () => {
    let needAddDetailMark = "";
    const {detailMap} = base.layoutStore;
    detailMap.forEach((detailObj, detailMark) => {
        const {attr, rowInfoArr} = detailObj;
        if (attr.isneed === 1 && rowInfoArr.length === 0 && needAddDetailMark === "") {
            const detailIndex = parseInt(detailMark.replace("detail_", "")) - 1;
            const detailLocTr = window.jQuery("#oTable"+detailIndex).closest(".wf-detail").closest("tr");
            if(detailLocTr.length > 0 && detailLocTr.css("display") !== "none"){
                needAddDetailMark = detailMark;
                return false;
            }
        }
    });
    if (needAddDetailMark !== "") {
        Util.showPrompt(needAddDetailMark, 3);
        return false;
    } else
        return true;
}

//提交校验字段必填范围
export const verifyRequiredEmptyField = () => {
    let emptyField = "";
    const {fieldAttrMap, cellInfo, mainData, detailMap, variableMap} = base.layoutStore;
    //联动隐藏行中的其它字段，忽略校验必填
    let ignoreVerifyRange = [];
    const reg = /^field\d+_viewAttr$/;
    variableMap.forEach((v, k) => {
        if (reg.test(k)) {
            const fieldid = k.match(/\d+/)[0];
            if (v === 4) {    //隐藏内容
                ignoreVerifyRange.push(fieldid);
            } else if (v === 5) {  //隐藏行
                const rowMark = _.get(cellInfo, ["fieldCellInfo", fieldid, "rowMark"]);
                rowMark && rowMark.split(",").forEach(item =>{
                    const rowFields = _.get(cellInfo, ["mainRowFields", item]) || [];
                    ignoreVerifyRange = ignoreVerifyRange.concat(rowFields);
                });
            }
        }
    });
    //计算明细需要校验的行号
    let detailVerifyRowIndexStr = {};
    detailMap.forEach((detailObj, detailMark) => {
        const {attr, rowInfo} = detailObj;
        let rowIndexStr = "";
        rowInfo.forEach((v, k) => {
            const keyid = v.has("keyid") ? parseInt(v.get("keyid")) : -1;
            if (keyid <= 0 || (keyid > 0 && attr.isedit === 1))
                rowIndexStr += k.substring(4) + ",";
        });
        if (rowIndexStr !== "")
            rowIndexStr = rowIndexStr.substring(0, rowIndexStr.length - 1);
        detailVerifyRowIndexStr[detailMark] = rowIndexStr;
    });
    //校验必填字段的范围
    let verifyRange = [];
    const fieldCellInfo = cellInfo.fieldCellInfo || {};
    _.forIn(fieldCellInfo, (v, fieldid) => {
        const orderid = v.orderid || 0;
        if (!fieldAttrMap.has(fieldid))
            return true;
        const fieldAttr = fieldAttrMap.get(fieldid);
        const isDetail = fieldAttr.isDetail;
        const tableMark = fieldAttr.tableMark;
        const {htmltype, detailtype} = fieldAttr;
        //Check框等类型、联动隐藏的行字段不校验必填
        if (htmltype === 4 || htmltype === 7 || htmltype === 8 || htmltype === 9 || fieldid === "-9"
            || (!isDetail && _.indexOf(ignoreVerifyRange, fieldid) > -1))
            return "";
        //附件上传未设置固定目录的不校验必填
        if (htmltype === 6 && _.get(fieldAttr, ["fileattr", "catelogType"]) === 0 && _.trim(_.get(fieldAttr, ["fileattr", "docCategory"])) === "")
            return "";
        //主字段，API隐藏的区域内字段不校验必填，兼容E8
        if(!isDetail && jQuery(`.field${fieldid}_swapDiv`).length > 0){
            const fieldSwapObj = jQuery(`.field${fieldid}_swapDiv`);
            if(fieldSwapObj.is(".filter_required") || fieldSwapObj.closest("tr").is(".filter_required"))
                return "";
        }
        const rowIndexStr = isDetail ? detailVerifyRowIndexStr[tableMark] : "-1";
        !!rowIndexStr && rowIndexStr.split(",").map(rowIndex => {
            const fieldMark = isDetail ? `field${fieldid}_${rowIndex}` : `field${fieldid}`;
            const fieldObj = FieldUtil.getFieldObj(fieldMark, tableMark);
            const {variable} = fieldObj;
            let needVerify = false;
            if (variable.has("viewAttr") && variable.get("viewAttr") > 0) {    //显示属性联动控制必填
                needVerify = variable.get("viewAttr") === 3;
            } else {
                needVerify = fieldAttr.viewattr === 3;
            }
            if (needVerify)
                verifyRange.push({fieldid, rowIndex, orderid:(orderid+parseInt(isDetail ? rowIndex : 0)), fieldObj, fieldAttr});
        });
    });
    verifyRange = verifyRange.sort((a, b) => {
        return a.orderid - b.orderid;
    });
    //根据范围依次校验值是否填写
    let emptyTableMark = "";
    let emptyRowIndex = "";
    for (let i = 0; i < verifyRange.length; i++) {
        const {fieldid, rowIndex, fieldObj, fieldAttr} = verifyRange[i];
        const {htmltype, detailtype, isDetail, tableMark} = fieldAttr;
        const fieldMark = isDetail ? `field${fieldid}_${rowIndex}` : `field${fieldid}`;
        let fieldValue = fieldObj.value;
        if(fieldid == -4){
            fieldValue = window.CK_REF.remark.getData() || "";
        }else if(htmltype === 2 && detailtype === 2){
            if(window.FORM_CK_REF && window.FORM_CK_REF[`field${fieldid}`]){
                fieldValue = window.FORM_CK_REF[`field${fieldid}`].getData() || "";
                fieldValue = fieldValue.replace(/<p>/ig, '').replace(/<\/p>/ig, '').replace(/ /ig, "").replace(/&nbsp;/ig, "").replace(/<br \/>/ig, "");
            }
        }
        fieldValue = _.trim(fieldValue);
        if (fieldValue === "") {
            emptyField = fieldMark;
            emptyTableMark = tableMark;
            emptyRowIndex = rowIndex;
            break;
        }
    }
    //明细字段分页情况需跳转至指定页
    if(emptyTableMark.indexOf("detail") > -1){
        const detailObj = DetailUtil.getDetailObj(emptyTableMark);
        detailObj.jumpPageByRowIndex(emptyRowIndex);
    }
    return emptyField;
}

//除表单字段外提交表单时的必填校验
export const verifyRequiredEmptyOtherParams = () =>{
    const { commonParam ,submitParam} = base.globalStore;
    const {showFreeWfSimpleCom}=commonParam;
    let obj={}
    if(showFreeWfSimpleCom != 0){
        const {conditionData={}} = base.freeWflowSimpleStore;
        //判断节点操作者是否必填
        let isMustInput=false;
        const {conditioninfo=[]} = conditionData;
        if(conditioninfo[0]) {
            const {items=[]}=conditioninfo[0];
            items.map(item=>{
                if(item.domkey[0]==="nodeOperator"&&item.viewAttr==3)
                    isMustInput=true;
            })
            if(Number(submitParam.isToNewAddSign) < 2 && submitParam.operatorids == "" && isMustInput){
                obj.scrollDom = '.wf-req-freeWorkflowSimple';
                obj.msg = getLabel(512971, "请选择节点操作者");
            }
        }
    }
    return obj;
}

//验证流程标题必填
export const verifyRequestNameIsEmpty = () => {
    const {mainData} = base.layoutStore;
    const fieldValue = mainData.has("field-1") ? mainData.get("field-1").value : "";
    return _.trim(fieldValue) === "";
}

//生成表单字段提交参数
export const generateFormData = () => {
    let datas = {};
    const {fieldAttrMap, mainData, detailMap, existChangeRange} = base.layoutStore;
    datas.existChangeRange = existChangeRange.join(",");
    mainData.forEach((fieldObj, k) => {
        const fieldname = FieldUtil.convertSystemFieldName(k);
        if (window.FORM_CK_REF && window.FORM_CK_REF[fieldname]) {    //富文本
            if(!!window.FORM_CK_REF[fieldname])
                datas[fieldname] = window.FORM_CK_REF[fieldname].getData();
            else
                datas[fieldname] = fieldObj.value;
        } else {
            const fieldid = k.substring(5);
            addCustomizeBrowserNames(datas, fieldAttrMap, fieldid, fieldObj, -1);
            datas[fieldname] = fieldObj.value;
        }
        //多人力分组信息
        if (fieldAttrMap.has(k.substring(5))) {
            const fieldAttr = fieldAttrMap.get(k.substring(5));
            if (fieldAttr.htmltype === 3 && fieldAttr.detailtype === 17) {
                const groupInfo = FieldUtil.buildMultiUserGroupInfo(fieldObj);
                const groupnum = groupInfo.groupnum;
                for (let i = 0; i < groupnum; i++) {
                    if (`group_${i}` in groupInfo)
                        datas[`${fieldname}group${i}`] = groupInfo[`group_${i}`];
                }
                datas[`${fieldname}groupnum`] = groupnum;
            }
        }
    });
    let detailFieldDatas = {};      //request请求参数个数有限制，重要参数往前提
    detailMap.forEach((detailObj, detailMark) => {
        const detailIndex = parseInt(detailMark.substring(7)) - 1;
        const {indexnum, deldtlid, detailData, rowInfo, fieldInfo} = detailObj;
        let submitidArr = new Array();
        let nodesnum = 0;
        rowInfo.forEach((info, rowKey) => {
            nodesnum++;
            const rowIndex = rowKey.substring(4);
            submitidArr.push(rowIndex);
            if (info.has("keyid"))
                datas[`dtl_id_${detailIndex}_${rowIndex}`] = info.get("keyid");
            _.forIn(fieldInfo, (v, fieldid) => {
                const fieldMark = `field${fieldid}_${rowIndex}`;
                if (detailData.has(fieldMark)) {
                    const fieldObj = detailData.get(fieldMark);
                    detailFieldDatas[fieldMark] = fieldObj.value;
                    addCustomizeBrowserNames(detailFieldDatas, fieldAttrMap, fieldid, fieldObj, rowIndex);
                }
            });
        });
        datas[`nodesnum${detailIndex}`] = nodesnum;
        datas[`indexnum${detailIndex}`] = indexnum;
        let submitdtlid = "";
        submitidArr.sort((a, b) => {
            return parseInt(a) - parseInt(b);
        }).map(_id => {
            submitdtlid += _id + ",";
        });
        datas[`submitdtlid${detailIndex}`] = submitdtlid;
        datas[`deldtlid${detailIndex}`] = deldtlid;
    });
    return {...datas, ...detailFieldDatas};
}

const addCustomizeBrowserNames = (datas = {}, fieldAttrMap, fieldid, fieldObj, rowIndex = -1) => {
    const fieldAttr = fieldAttrMap.get(fieldid);
    if (fieldAttr) {
        if (fieldAttr.htmltype === 3 && (fieldAttr.detailtype === 161 || fieldAttr.detailtype === 162)) {
            const specialobj = fieldObj.specialobj || [];
            if (specialobj && specialobj.length > 0) {
                const namesplitstr = '##~~@@~~##';
                const fieldnameArr = [];
                specialobj.forEach((vObj, index) => {
                    fieldnameArr.push(vObj.name);
                })
                let key = `field${fieldid}name`;
                if (rowIndex > -1) key = `field${fieldid}_${rowIndex}name`;
                datas[key] = fieldnameArr.join(namesplitstr);
            }
        }
    }
}

//生成自由流程提交参数
export const generateFreeNodeData = (isFree) => {
    let freeNodeInfo = {};
    if (isFree == "1") {
        jQuery('.freeNode').find('input').map((o, k) => {
            freeNodeInfo[k.name] = k.value;
        });
    }
    return freeNodeInfo;
}

export const getRemarkQuoteData = () => {
    const {submitParam, variableMap, dialogVisible} = base.globalStore;
    const remark = submitParam.remark || '';
    let remarkList = mobx.toJS(variableMap.get('remark_list')||{});
    if(dialogVisible.has( type.FREE_WORKFLOW_SIMPLE ) && dialogVisible.get( type.FREE_WORKFLOW_SIMPLE )){
        remarkList = mobx.toJS(variableMap.get('remark_list_freeWorkflowSimple')||{});
    }
    let remarkQuoteData = [];
    _.forIn(remarkList,(v,k)=>{
        remarkQuoteData.push(v);
    })
    let remarkTemp = remarkQuoteData.length>0 ? remarkQuoteData.join('') + "\n" + remark : remark;
    let updateParams = {remark:remarkTemp};
    let remarkquote = {remark,remarkquote:remarkQuoteData.join('~~~~@@@@~~~~@@@@@~~~~')};
    return {remark:remarkTemp,remarkquote:JSON.stringify(remarkquote)};
}

/**
 * 主干节点提交时确认是否走分支
 * @param params
 * @return {*}
 */
const getNeedFlowFreeNodeTips = (params = {}) => {
    const {changeSubmitParam} = base.globalStore;
    changeSubmitParam({'flowToNextFreeNode':'0'});
    const {Radio} = getAntd();
    const RadioGroup = Radio.Group;
    return (
        <div>
        <div>{`${getLabel(507410,'请选择流转路径')}:`}</div>
    <div style={{'marginTop':'10px'}}>
<RadioGroup ecId={`${this && this.props && this.props.ecId || ''}_RadioGroup@thusyj`} onChange={(e)=> changeSubmitParam({'flowToNextFreeNode':e.target.value})} defaultValue = {'0'}>
        <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@1f0s3u`} value={'0'}>{getLabel(507411,'流转至下一节点')}</Radio>
    <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@o2uufy`} value={'1'}>{getLabel(507412,'进入加签环节')}</Radio>
    </RadioGroup>
    </div>
    </div>
)
}

const jundgeNeedFlowFreeNodeTips = (src,needconfirm = false,selectNextFlow) =>{
    if(selectNextFlow == '1') return false;
    let needTips = (src == 'submit' && !needconfirm) || (src == 'save' && needconfirm);
    if(!needTips) return false;
    const {commonParam,variableMap,submitParam} = base.globalStore;
    let {isNeedFlowFreeNodeTips = false} = commonParam;
    let {SubmitToNodeid = ''} = submitParam;

    //提交至退回节点
    if(SubmitToNodeid > 0 || SubmitToNodeid < -1) {
        return false;
    }

    //流程图保存后返回的实时参数
    if(variableMap.has('isNeedFlowFreeNodeTips')) {
        isNeedFlowFreeNodeTips = variableMap.get('isNeedFlowFreeNodeTips');
    }

    if(isNeedFlowFreeNodeTips && variableMap.has('wflinkTipOkCount')) {
        isNeedFlowFreeNodeTips = variableMap.get('wflinkTipOkCount') == 0;
    }
    return isNeedFlowFreeNodeTips;
}